<template>
  <view class="detail-container">

    <scroll-view 
      class="content-scroll" 
      scroll-y 
      :refresher-enabled="true"
      @refresherrefresh="onRefresh"
    >
      <!-- 统一内容容器 -->
      <view class="content-wrapper">
        <uni-load-more 
          v-if="loading" 
          status="loading" 
          :contentText="{ contentdown: '下拉刷新', contentrefresh: '正在加载' }"
        />

        <template v-if="!error && !loading">
          <view class="article-header">
            <text class="title">{{ detailData.title }}</text>
            <view class="meta">
              <text class="author">{{ detailData.author }}</text>
              <text class="time">{{ formatTime(detailData.publishTime) }}</text>
            </view>
          </view>

          <image 
            v-if="detailData.cover" 
            :src="detailData.cover" 
            mode="widthFix" 
            class="cover-image"
            @error="handleImageError"
          />

          <view class="rich-content-wrapper">
            <rich-text 
              :nodes="parseContent(detailData.content)" 
              class="rich-content"
            />
          </view>
        </template>

        <view v-else-if="error" class="error-container">
          <uni-icons type="info" size="60" color="#999" />
          <text class="error-text">内容加载失败</text>
          <button class="retry-btn" @click="loadDetail">重试</button>
        </view>
      </view>
    </scroll-view>
	
	<view class="action-bar">
	  <!-- 收藏按钮 -->
	  <view 
		class="action-item like-btn" 
		:class="{ 'active': isLiked }"
		@tap="toggleLike"
		hover-class="btn-hover"
	  >
		<view class="icon-wrapper">
		  <uni-icons 
			:type="isLiked ? 'heart-filled' : 'heart'" 
			:color="isLiked ? '#e64340' : '#666'"
			size="24"
		  />
		</view>
		<text class="action-text">{{ isLiked ? '已收藏' : '收藏' }}</text>
	  </view>

	  <!-- 分享按钮 -->
		<view class="action-item share-btn">
		  <button 
			class="share-button" 
			open-type="share"
			hover-class="none"
			@tap="handleShareTap"
		  >
			<view class="icon-wrapper">
			  <uni-icons type="share" color="#666" size="24" />
			</view>
			<text class="action-text">分享</text>
		  </button>
		</view>

	</view>

  </view>
</template>

<script>
export default {
  data() {
    return {
      detailData: {
        title: '',
        content: '',
        author: '',
        publishTime: '',
        cover: ''
      },
      articleId: null,
      loading: true,
      error: false,
      isLiked: false
    }
  },
  onLoad(options) {
    this.articleId = Number(options.id) || 0
    if (!this.articleId) {
      uni.showToast({ title: '无效文章ID', icon: 'none' })
      setTimeout(() => uni.navigateBack(), 1500)
      return
    }
    this.loadDetail()
  },
  onShareAppMessage() {
    return {
      title: this.detailData.title || '健康文章分享',
      path: `/pages/detail/detail?id=${this.articleId}`,
      imageUrl: this.detailData.cover || '/static/share-default.jpg'
    }
  },
  methods: {
    async loadDetail() {
      this.loading = true
      this.error = false
      
      try {
        const res = await uni.request({
          url: `http://localhost:8088/api/articles/detail/${this.articleId}`,
          method: 'GET',
          timeout: 8000
        })

        if (res.statusCode !== 200 || !res.data?.data) {
          throw new Error(res.data?.message || '数据加载异常')
        }

        const articleData = res.data.data
        
        this.detailData = {
          title: articleData.title || '无标题',
          content: articleData.content || '',
          author: articleData.author || '匿名作者',
          publishTime: articleData.publishTime,
          cover: articleData.cover || ''
        }

        this.isLiked = !!articleData.isLiked
      } catch (e) {
        console.error('加载失败:', e)
        this.error = true
        uni.showToast({ title: e.message || '加载失败', icon: 'none' })
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    parseContent(content) {
      const safeContent = String(content || '')
      try {
        return safeContent
          .replace(/\r\n/g, '<div class="line-break"></div>')
          .replace(/\n/g, '<div class="line-break"></div>')
          .replace(/<p/g, '<div class="paragraph"')
          .replace(/<\/p>/g, '</div>')
          .replace(/<img/gi, '<img class="rich-img"')
          .replace(/<table/gi, '<div class="table-container"><table')
          .replace(/<\/table>/gi, '</table></div>')
          .replace(/<(\w+)(?=[^>]*?)(?<!\/)>/g, '<$1>')
      } catch (e) {
        return '<div class="error-text">内容解析错误</div>'
      }
    },
	formatTime(timeStr) {
	  // 空值处理
	  if (!timeStr) return '未知日期';

	  try {
		// 创建日期对象（兼容iOS）
		const date = new Date(timeStr.replace(' ', 'T')); // 处理空格分隔的格式
		
		// 有效性验证
		if (isNaN(date.getTime())) throw new Error('无效日期');

		// 手动格式化年月日
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
		const day = String(date.getDate()).padStart(2, '0');

		return `${year}-${month}-${day}`;
	  } catch (e) {
		console.warn('日期处理失败:', { input: timeStr, error: e.message });
		return '日期无效';
	  }
	},

    handleImageError() {
      this.detailData.cover = '/static/default-cover.jpg'
    },

    onRefresh() {
      this.loadDetail()
    },

    async toggleLike() {
      try {
        const { statusCode } = await uni.request({
          url: `/api/like/${this.articleId}`,
          method: 'POST',
          data: { status: !this.isLiked }
        })
        
        if (statusCode === 200) {
          this.isLiked = !this.isLiked
          uni.showToast({
            title: this.isLiked ? '收藏成功' : '已取消收藏',
            icon: 'none'
          })
        }
      } catch (e) {
        uni.showToast({ title: '操作失败', icon: 'none' })
      }
    },
	// 在methods中添加：
	handleShareTap() {
	  // 触发分享菜单
	  uni.showShareMenu({
	    withShareTicket: true,
	    menus: ['shareAppMessage', 'shareTimeline']
	  });
	},
	
	// 完善onShareAppMessage
	onShareAppMessage(res) {
	  if (res.from === 'button') {
	    console.log('来自页面内转发按钮');
	  }
	  return {
	    title: this.detailData.title || '健康知识分享',
	    path: `/pages/home/detail/detail?id=${this.articleId}`,
	    imageUrl: this.detailData.cover || '/static/share-default.jpg',
	    success: (res) => {
	      uni.reportAnalytics('article_share', {
	        article_id: this.articleId
	      });
	    },
	    fail: (err) => {
	      console.error('分享失败:', err);
	    }
	  };
	},


    navigateBack() {
      uni.navigateBack({ delta: 1 })
    }
  }
}
</script>

<style scoped>
/* 修复后的样式 */
.detail-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

/* 导航栏样式 */
::v-deep .uni-nav-bar__header {
  padding: 0 32rpx !important;
  height: 88rpx !important;
  border-bottom: 1rpx solid #eee !important;
}




/* 内容容器 */
.content-scroll {
  flex: 1;
  padding-bottom: 120rpx;
}

.content-wrapper {
  padding: 0 32rpx;
}

/* 文章标题区域 */
.article-header {
  padding-top: 40rpx;
  margin-bottom: 48rpx;
}

.title {
  font-size: 48rpx;
  line-height: 1.5;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

.meta {
  display: flex;
  gap: 32rpx;
  font-size: 28rpx;
  color: #999;
}

/* 图片样式 */
.cover-image {
  width: 100%;
  border-radius: 16rpx;
  margin: 32rpx 0;
  background: #f5f5f5;
}

/* 富文本容器 */
.rich-content-wrapper {
  padding: 20rpx 0 80rpx;
}

.rich-content {
  line-height: 1.8;
  font-size: 34rpx;
  color: #444;
}

/* 深度样式调整 */
.rich-content >>> .paragraph {
  margin: 1em 0;
}

.rich-content >>> .rich-img {
  width: 100% !important;
  height: auto !important;
  margin: 40rpx 0;
  border-radius: 12rpx;
  background: #f5f5f5;
}

.rich-content >>> .table-container {
  width: 100%;
  overflow-x: auto;
  margin: 40rpx 0;
}

.rich-content >>> .custom-table {
  min-width: 100%;
  border-collapse: collapse;
}

.rich-content >>> .table-cell {
  padding: 16rpx;
  border: 1rpx solid #e0e0e0;
}

/* 错误提示 */
.error-container {
  padding: 120rpx 32rpx;
  text-align: center;
}

/* 操作栏 */
.action-bar {
  display: flex;
  padding: 16rpx 32rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.02);
}

.action-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  border-radius: 16rpx;
  transition: all 0.2s cubic-bezier(0.18, 0.89, 0.32, 1.28);
}

/* 微信风格点击反馈 */
.btn-hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.icon-wrapper {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.02);
}

.action-text {
  font-size: 24rpx;
  color: #666;
  margin-top: 8rpx;
}

/* 激活状态 */
.active .icon-wrapper {
  background: rgba(230, 67, 64, 0.1);
}
.active .action-text {
  color: #e64340;
  font-weight: 500;
}

/* 适配暗色模式 */
@media (prefers-color-scheme: dark) {
  .action-bar {
    background: #1a1a1a;
    border-color: #333;
  }
  
  .icon-wrapper {
    background: rgba(255, 255, 255, 0.05);
  }
  
  .action-text {
    color: rgba(255, 255, 255, 0.7);
  }
  
  .btn-hover {
    background-color: rgba(255, 255, 255, 0.1);
  }
}

</style>